<template>
	<div>
		<StepTabs :tabs="tabsList" v-model="activeIndex"></StepTabs>
		<div class="from-content" v-if="activeIndex == 1">
			<AplidForm ref="formRef" v-bind="formProjectConfig(subsidyType)" v-model="formModel" @submit="onSubmit">
				<template v-slot:subsidyApplyConfigIdForm>
					<remoteSelect
						class="w-100"
						:disabled="!formModel.subsidyType"
						:key="formModel.subsidyType"
						:paramsObj="{ subsidyType: formModel.subsidyType, isAuthFilter: false, organizationId: userInfo.organizationId }"
						api="view_ofsSubsidyProject_page"
						filterKey="subsidyApplyConfigId"
						filterLabel="projectName"
						propName="projectName"
						placeholder="请选择"
						v-model:modelName="formModel.subsidyProjectName"
						v-model="formModel.subsidyApplyConfigId"
						@change="handleGetProjectInfo"
					></remoteSelect>
				</template>
			</AplidForm>
			<div class="footer-btn fc">
				<el-button @click="formRef.onSubmit()" type="primary">下一步</el-button>
			</div>
		</div>

		<template v-if="activeIndex == 2">
			<div class="config-content">
				<policyArchive :list="nowData.policyRel"></policyArchive>
			</div>
			<div class="footer-btn">
				<div class="block">
					<span class="label">申请日期</span>
					<el-date-picker
						v-model="formModel.belongDate"
						:disabled-date="disabledDate"
						type="month"
						value-format="YYYY-MM-DD"
						placeholder="请选择日期"
					/>
				</div>
				<div class="w-100 fc">
					<el-button @click="handleProd">上一步</el-button>
					<el-button type="primary" @click="handleNext">下一步</el-button>
				</div>
			</div>
		</template>

		<template v-if="activeIndex == 3">
			<!-- <ApplyReport :nowRowData="{...nowData,...formModel}" @refresh-change="onRefreshChange"></ApplyReport> -->
			<ApplyPerson ref="table" :nowRowData="{ ...nowData, ...formModel }" @backData="backData"></ApplyPerson>
			<div class="footer-btn">
				<div class="w-100 fc">
					<el-button @click="handleProd">上一步</el-button>
					<el-button type="primary" @click="handleSubmitApply">提交申请</el-button>
				</div>
			</div>
		</template>
	</div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import apiMod from '@/apiMod/index'
import remoteSelect from '@/components/AplidCrud/src/AplidRemote/index'
import StepTabs from '@/views/instOperate/components/StepTabs/index.vue'
import policyArchive from '@/views/instOperate/components/policyArchive/index.vue'
import ApplyPerson from './ApplyPerson/index.vue'
import { formProjectConfig } from '../config'
import { getStore } from '@/utils/store'
import { md5 } from '@/utils/encdecrpt'

const props = withDefaults(
	defineProps<{
		subsidyType?: string
		nowRowData?:any
	}>(),
	{
		subsidyType: '9',
		nowRowData:{}
	}
)
const emit = defineEmits(['refresh'])
const formModel: any = ref({
	belongDate: '',
	subsidyType: props.subsidyType,
})

let projectDate = ref({
	projectStartDate: '',
	projectEndDate: '',
})
const disabledDate = (date) => {
	let startDate = new Date(projectDate.value.projectStartDate)
	let endDate = new Date(projectDate.value.projectEndDate)
	let month = date.getMonth() + 1
	return (month != 4 && month != 10) || date.getTime() > new Date() || date.getTime() < startDate || date.getTime() > endDate
}
const userInfo = getStore('userInfo') || {}
const formRef = ref(null)
const activeIndex = ref(1)

const tabsList = [
	{ label: '01.选择补贴项目', value: 1, tip: '选择对应的补贴项目' },
	{ label: '02.申请须知', value: 2, tip: '关于申请养老扶助对象入住养老机构减免、冲抵费用的政策文件' },
	{ label: '03.提交材料', value: 3, tip: '根据政策文件，提供相关文件' },
]

const nowData: any = ref({})

const handleNext = () => {
	if (!formModel.value.belongDate) {
		ElMessage.warning('请选择申请日期')
		return
	}
	nowData.value.belongDate = formModel.value.belongDate

	const getYearMonth = (belongDate) => {
		const year = belongDate.replace('年', '-').replace('月', '').split('-')[0]
		const month = belongDate.replace('年', '-').replace('月', '').split('-')[1]
		return { year, month }
	}
	apiMod
		.view_subsidy_getData({
			projectId: formModel.value.subsidyProjectId,
			creditCode: userInfo.organizationId,
			...getYearMonth(formModel.value.belongDate),
		})
		.then((res) => {
			if (res.data == 0) {
				onNext()
			} else {
				ElMessage.warning('该项目已存在申请，请勿重复申请！')
			}
		})
}

const onNext = () => {
	if (activeIndex.value < tabsList.length) {
		activeIndex.value += 1
	}
}

const handleGetProjectInfo = (data) => {
	if (data) {
		projectDate.value.projectStartDate = data.projectStartDate
		projectDate.value.projectEndDate = data.projectEndDate
		formModel.value.subsidyProjectId = data.id
	}
}
const handleProd = () => {
	if (activeIndex.value > 1 && activeIndex.value <= tabsList.length) {
		activeIndex.value -= 1
	}
	if (activeIndex.value == tabsList.length - 1) {
		table.value.getBackData()
	}
}
const onSubmit = (form, done) => {
	// 获取项目配置
	apiMod.view_ofsSubsidyApplyConfig_view(form.subsidyApplyConfigId).then((res) => {
		nowData.value = {
			...(res.data || {}),
		}
		onNext()
	})

	done()
}

const onRefreshChange = (formId) => {
	formModel.value.applyNo = formId
}
let finallData = reactive([])

const handleSubmitApply = async () => {
	let tableData = formModel.value.tableData
	if (tableData) {
		if (!tableData.r0c1 && tableData.r0c1 != 0) {
			ElMessage.error(`请查看${tableData.oneVal}申请名单后再次提交`)
		} else if (!tableData.r1c1 && tableData.r1c1 != 0) {
			ElMessage.error(`请查看${tableData.twoVal}申请名单后再次提交`)
		} else if (!tableData.r2c1 && tableData.r2c1 != 0) {
			ElMessage.error(`请查看${tableData.threeVal}申请名单后再次提交`)
		} else if (!tableData.r3c1 && tableData.r3c1 != 0) {
			ElMessage.error(`请查看${tableData.fourVal}申请名单后再次提交`)
		} else if (!tableData.r4c1 && tableData.r4c1 != 0) {
			ElMessage.error(`请查看${tableData.fiveVal}申请名单后再次提交`)
		} else if (!tableData.r5c1 && tableData.r5c1 != 0) {
			ElMessage.error(`请查看${tableData.sixVal}申请名单后再次提交`)
		} else {
			// 如果合计金额为0，就不能提交
			if (tableData.r6c9 == 0||tableData.r6c9=='0.0') {
				ElMessage.error('无数据，不可提交')
			} else {
				const params: any = {
					belongDate: formModel.value.belongDate,
					creditCode: formModel.value.tableData.creditCode,
					subsidyProjectId: formModel.value.subsidyProjectId,
					applyNo: formModel.value.applyNo,
				}
				if (!formModel.value.applyNo) {
					const str = [params?.creditCode, params?.belongDate?.replace('-', '').substring(0, 6), params?.subsidyProjectId].filter(Boolean).join('_')
					params.applyNo = md5(str)
				}
				let caseId = formModel.value.tableRel?JSON.parse(formModel.value.tableRel):[]
				let params0 = {
					dataContent: formModel.value.tableData,
					dataResults: formModel.value.tableData,
					applyYear: formModel.value.belongDate.split('-')[0],
					applyMonth: formModel.value.belongDate.split('-')[1],
					fromId: params.applyNo,
					fromType: caseId[0]?.value,
					tableTemplateId: caseId[0]?.value,
					projectId: formModel.value.subsidyProjectId,
				}
				console.log('厉害',params0)
				// 保存一下表格
				await apiMod.view_formResults_add(params0)
				// 提交数据
				let resp = await apiMod.view_ofsSubsidyApply_add(params)
				ElMessage.success('提交成功')
				emit('refresh')
			}
		}
	} else {
		ElMessage.error(`请查看申请名单后再次提交`)
	}
}
let table = ref()
// 选择申请对象时返回的数据
const backData = (data) => {
	formModel.value = data
}

watch(
	() => formModel.value.subsidyType,
	() => {
		formModel.value.subsidyProjectName = undefined
		formModel.value.subsidyApplyConfigId = undefined
	},
	{
		immediate: true,
	}
)
</script>

<style scoped lang="scss">
.from-content {
	width: 50%;
	margin: 100px auto;
}
.config-content {
	padding: 12px;
	margin-top: 20px;
	border: 1px solid #dcdcdc;
	border-radius: 10px;
}
.footer-btn {
	margin-top: 32px;
	.block {
		display: flex;
		align-items: center;
		.label {
			margin-right: 12px;
		}
	}
}
</style>
